package com.example.administrator.newjiajiesong.network;


import com.example.administrator.newjiajiesong.network.http.LifeTreeAPIException;
import com.example.administrator.newjiajiesong.network.http.ResponseBean;
import com.example.administrator.newjiajiesong.utils.checkVersionsUtils.ProfileSpUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;


/**
 * ApiCallBack
 * 类描述: 网络请求结果的二次封装
 * 作者: xiaoyu on 2016/12/29 13:40
 */

public abstract class ApiCallBack<T> {

    protected abstract void onSuccess(T responseData, String message);

    protected abstract void onFailure(String error);

    public void onResponse(final ResponseBean<T> responseBean) {
        if (responseBean == null) {
            //接口崩溃
            onFailure("系统错误");
            return;
        }
        //数据结果分类
//        if (responseBean.getStatus() == ResponseBean.SUCCESS) {
//            onSuccess(responseBean.getData(), responseBean.getMsg());
//        } else if (responseBean.getStatus() == ResponseBean.ERROR) {
//            if ("用户不存在".equals(responseBean.getMsg()) || "\\u7528\\u6237\\u4e0d\\u5b58\\u5728".equals(responseBean.getMsg())) {
//                // TODO: 2017/4/28  用户被挤下线,让用户重新登录
//                ProfileSpUtils.getInstance().saveLoginSatus(false);
//                onFailure("您没有登录或您的登录信息过期,请重新登录");
//            } else {
//                //其他错误信息提示
//                onFailure(responseBean.getMsg());
//            }
//        }

    }

    /**
     * 请求失败
     *
     * @param throwable
     */
    public void onFailure(final Throwable throwable) {
        throwable.printStackTrace();
        if (throwable instanceof HttpException) {
            HttpException httpException = (HttpException) throwable;
            int code = httpException.code();
            if (code == 500 || code == 404) {
                onFailure("服务器出错");
            }
        } else if (throwable instanceof ConnectException) {
            onFailure("网络断开,请打开网络!");
        } else if (throwable instanceof SocketTimeoutException) {
            onFailure("网络连接超时!!");
        } else if (throwable instanceof LifeTreeAPIException) {
            onFailure(throwable.getMessage());
        } else if (throwable instanceof UnknownHostException) {
            onFailure("网络断开,请打开网络!");
        } else {
            onFailure("发生未知错误" + throwable.getMessage());
        }
    }
}